PhotoEffect = Class.create();

Object.extend(PhotoEffect.prototype, {
  reload : 0,
  framed : false,
  target : '',
  rotate : 0,

  initialize: function(){
  },
  
  execute: function(target, rot, framepath){
    this.reload = 0;
    this.photoframe = new Image();
    this.photoframe.src = framepath;
    var _this = this;
    this.photoframe.onload = function(){
      if(_this.photoframe.width){
        _this.framed = true;
      }
    };
    this.target = target;
    this.rotate = rot;
    this.intarval(1000);
  },
  
  intarval : function(limit){ 
    var _this = this;
    var _timer_photoEffect = setInterval(function(){
        if(_this.framed){
          clearInterval(_timer_photoEffect);
          _this.fire();
        }
        if(_this.reload >= limit){
          clearInterval(_timer_photoEffect);
          alert('Timeout! Check frame-image files.');
        }
        _this.reload++;
      }, 10);
  },
  
  fire : function() {
    var d = document, img, ix, iy, iw, ih, rot, dx, dy, bx, by, fw, fh, w, h, frame, canvas, cntxt;
    img = document.getElementById(this.target);
    iw = img.width; ih = img.height;
    if ( this.rotate != undefined ) {
      rot = this.rotate;
    } else {
      rot = 0;
    }
    if(rot > 0){
      dx = parseInt(Math.sin(rot) * ih); dy = 0;
    } else {
      dx = 0; dy = parseInt(Math.sin(-rot) * iw);
    }
    //firefox only
    frame = this.photoframe;
    bx = parseInt(Math.sqrt(iw)*.8); by = parseInt(Math.sqrt(ih)*.8);
    fw = iw + bx * 2; fh = ih + parseInt(by * 3.7) + dy;
    ix = bx + dx; iy = parseInt(by*1.3) + dy + 2;
    w = parseInt(Math.sin(Math.abs(rot)) * fh) + fw;
    h = parseInt(Math.sin(Math.abs(rot)) * fw) + parseInt(Math.cos(rot) * fh);
    canvas = d.createElement('canvas');
    canvas.style.cssText = img.style.cssText;
    canvas.title = img.title;
    canvas.height = h; canvas.style.height = h + 'px';
    canvas.width = w; canvas.style.width = w + 'px';
    cntxt = canvas.getContext('2d');
    img.parentNode.replaceChild(canvas, img);
    if(rot != 0) cntxt.rotate(rot);
    cntxt.drawImage(frame, dx, dy, fw, fh);
    cntxt.drawImage(img, ix, iy, iw, ih);
    if(img.getAttribute('onclick') != ''){
      canvas.setAttribute('onclick', img.getAttribute('onclick'));
    }
  }
})
